/*
 * Copyright 2013 Agustina Martinez-Garcia

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package uk.ljmu.metadata.utilities;

//import java.io.IOException;
//import java.net.HttpURLConnection;
//import java.net.MalformedURLException;
//import java.net.URI;
//import java.net.URISyntaxException;
//import java.net.URL;
//import java.net.URLConnection;
//import java.util.Iterator;
//import java.util.List;

//import org.apache.log4j.Logger;
//import org.dom4j.Document;
//import org.dom4j.DocumentException;
//import org.dom4j.DocumentHelper;
//import org.dom4j.Element;

public class RdfFunctions {
//private static final Logger log = Logger.getLogger(RdfFunctions.class);
//
//	
//	/**
//	 * Check if a given property ia already specified in an RDF record
//	 * 
//	 * @param elem XML element to check
//	 * @param propertyName name of the property to check existence
//	 * @param propertyValue value of the property
//	 
//	 * @return true if already present, false otherwise
//	 */
//	public static boolean checkPropertyExistence(Element elem, String propertyName, String propertyValue)
//	{
//		int prefixIndex = -1;
//		prefixIndex = propertyName.indexOf(":");
//
//		if (prefixIndex >= 0)
//			propertyName = propertyName.substring(prefixIndex + 1, propertyName.length());
//		Iterator<?> iter = elem.elementIterator(propertyName);
//
//		while (iter.hasNext())
//		{
//			Element elProp = (Element) iter.next();
//			String value = elProp.attributeValue("resource");
//			
//			//This statement is already present in the RELS_EXT datastream
//			if (value.compareToIgnoreCase(propertyValue) == 0)
//			{
//				//Don't add it and return
//				log.info("Duplicate property: " + propertyName + ", " + propertyValue);
//				return true;					
//			}
//		}
//		return false;
//	}
//	//SCHEMA AND RDF DOCUMENT MANAGEMENT METHODS
//	/**
//	 * Create an empty RDF document
//	 * @param objectPID pid of the object being described, rdf:about value
//	 * @param prefixs to include in the document
//	 *
//	 * @return RDF document
//	 */
//	public static Document contructRDFDocument(String objectPID, List<String> prefixs)
//	{
//		//Create document
//		Element root = DocumentHelper.createElement( "rdf:RDF" );
//		root.addNamespace("rdf", MetadataUtilities.RELS_MAP.get("rdf"));
//		if (prefixs != null && prefixs.size() > 0) {
//			for (String pref : prefixs)	{
//					String ns = MetadataUtilities.MDSchemasUrl.get(pref);
//					if (ns == null)
//						continue;
//					root.addNamespace(pref, ns);
//				}
//			}
//
//		Element description = DocumentHelper.createElement("rdf:Description");
//		description.addAttribute("rdf:about", !objectPID.startsWith("info") ? MetadataUtilities.OBJECTID + objectPID : objectPID);
//		root.add(description);
//		Document doc = DocumentHelper.createDocument(root);
//		
//		return doc;
//	}
//	
//	/**
//	 * Create an empty RDF document
//	 * @param objectPID pid of the object being described, rdf:about value
//	 * @param prefixs to include in the document
//	 *
//	 * @return RDF document
//	 */
//	public static Document contructRDFDocument(String objectPID, List<String> prefixs, String xmlDoc)
//	{
//		Document doc = null;
//		if (xmlDoc == "") {
//			//Create document
//			Element root = DocumentHelper.createElement( "rdf:RDF" );
//			root.addNamespace("rdf", MetadataUtilities.RELS_MAP.get("rdf"));
//			if (prefixs != null && prefixs.size() > 0) {
//				for (String pref : prefixs)	{
//						String ns = MetadataUtilities.MDSchemasUrl.get(pref);
//						if (ns == null)
//							continue;
//						root.addNamespace(pref, ns);
//					}
//				}
//	
//			Element description = DocumentHelper.createElement("rdf:Description");
//			description.addAttribute("rdf:about", !objectPID.startsWith("info") ? MetadataUtilities.OBJECTID + objectPID : objectPID);
//			root.add(description);
//			doc = DocumentHelper.createDocument(root);
//			
//		} else {
//			try {
//				doc = DocumentHelper.parseText(xmlDoc);
//			
//				Element root = doc.getRootElement();
//				if (prefixs != null && prefixs.size() > 0) {
//					for (String pref : prefixs)	{
//						String ns = MetadataUtilities.MDSchemasUrl.get(pref);
//						if (ns == null)
//							continue;
//						root.addNamespace(pref, ns);
//					}
//				}
//				
//			} catch (DocumentException e) {
//				log.fatal("In constructDocument, error while parsing from xml text");
//			}
//		}
//		return doc;
//	}
//	/**
//	 * Create an empty RDF document
//	 * @param prefixs to include in the document
//	 *
//	 * @return RDF document
//	 */
//	public static Document contructRDFDoc(List<String> prefixs)
//	{
//		//Create document
//		Element root = DocumentHelper.createElement( "rdf:RDF" );
//		root.addNamespace("rdf", MetadataUtilities.RELS_MAP.get("rdf"));
//
//		if (prefixs != null && prefixs.size() > 0)
//		{
//			for (String pref : prefixs)
//			{
//				String ns = MetadataUtilities.MDSchemasUrl.get(pref);
//				if (ns == null)
//					continue;
//				root.addNamespace(pref, ns);
//			}
//		}
//
//		
//		Document doc = DocumentHelper.createDocument(root);
//
//		return doc;
//	}
//	/**
//	 * Add a property to an existing RDF description record
//	 * 
//	 * @param propertyName string with the property name
//	 * @param propertyValue string with the value of the property
//	 * @param propertyType string containing the property range
//	 * @param xmlContents String containing the actual record in which to add the new property
//	 * 
//	 * @return Document with the properties added
//	 */
//	public static Document addRDFProperty(String propertyName, String propertyValue, String propertyType, String xmlContents)
//	{
//		//Create document
//		Document doc = null;
//		try 
//		{
//			doc = DocumentHelper.parseText(xmlContents);
//		} catch (DocumentException e) {
//			log.fatal(e.getMessage());
//		}
//		if (doc != null)
//		{
//			Element root = doc.getRootElement();
//			Element desc = root.element("Description");
//			Element property = DocumentHelper.createElement(propertyName);
//			if (propertyType == null) {
//				//AMG - We treat it as a literal
//				property.setText(propertyValue);
//				desc.add(property);
//				return doc;
//			}
//			//AMG - WILL HAVE TO MAKE USE OF THE ONTOLOGIES TO GUESS THE RDF ELEMENT NEEDED HERE
//			if (propertyType.equalsIgnoreCase("class") || propertyType.equalsIgnoreCase("resource")) {
//				//AMG - Check valid URI
//				if (RdfFunctions.checkValidURI(propertyValue))
//					property.addAttribute("rdf:resource", propertyValue);
//				else return doc;
//			}
//			else property.setText(propertyValue);
//			
//			desc.add(property);
//
//			return doc;
//		} 
//		else
//		{
//			log.info("Error while creating XML Document");
//			return null;
//		}
//	}
//
//	
//	//VARIOUS UTILITIES
//	/**
//	 * Check if the spreadsheet header is a valid header: element of a metadata schema
//	 * of special types of datastreams in Fedora.
//	 * 
//	 * @param ds_name string containing the header name
//	 * 
//	 * @return true if valid header, false otherwise
//	 */
//	public static boolean checkIsDataStream(String ds_name)
//	{
//		//Check if the header belongs to a Metadata schema
//		int index = ds_name.indexOf(":");
//		String schemaName, typeName = "";
//
//		if (index >= 0)
//		{
//			schemaName = ds_name.substring(0, index);
//			typeName = ds_name.substring(index + 1, ds_name.length());
//		}//The datastrean is neither datastream or schema element
//		else return false;
//
//		//Check if it's an schema element
//		String schemaElem = MetadataUtilities.MDSchemasUrl.get(schemaName);
//		if (schemaElem != null)
//			return false;
//		//Check if it's a valid datastream type
//		MetadataUtilities.ValueType elem = MetadataUtilities.ValueType.valueOf(typeName.toUpperCase());
//
//		if (elem != null)
//			return true;
//		else return false;		
//	}
//
//	/**
//	 * Method to check if an URL is valid
//	 * 
//	 * @param urlStr string containing the URL to check
//	 * @return true if valid, false otherwise
//	 */
//	public static boolean validateURL(String urlStr)
//	{
//		if (urlStr.equals(""))
//				return false;
//		URL url;
//		try {
//			url = new URL(urlStr);
//			URLConnection connection = url.openConnection();
//
//			if (connection instanceof HttpURLConnection) {
//				HttpURLConnection httpConnection = (HttpURLConnection) connection;
//				httpConnection.connect();
//				int response = httpConnection.getResponseCode();
//				log.info("Response: " + String.valueOf(response));
//			}
//		} catch (MalformedURLException e) {
//			return false;
//		} catch (IOException e) {
//			return false;
//		}
//		
//
//		return true;
//	}
//	
//	public static boolean checkValidURI(String strURI) {
//		try {
//			URI uri = new URI(strURI);
//			return uri.isAbsolute();
//		} catch (URISyntaxException e) {
//			return false;
//		}
//	}
////	public static boolean checkValidHttpURI(String strURI) {
////		String URL_REGEX = @"(?#WebOrIP)((?#protocol)((http|https):\\\/\\\/)?(?#subDomain)(([a-zA-Z0-9]+\\\.(?#domain)[a-zA-Z0-9\\\-]+(?#TLD)(\\\.[a-zA-Z]+){1,2})|(?#IPAddress)((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])))+(?#Port)(:[1-9][0-9]*)?)+(?#Path)((\/((?#dirOrFileName)[a-zA-Z0-9_\-\%\~\+]+)?)*)?(?#extension)(\.([a-zA-Z0-9_]+))?(?#parameters)(\?([a-zA-Z0-9_\-]+\=[a-z-A-Z0-9_\-\%\~\+]+)?(?#additionalParameters)(\&([a-zA-Z0-9_\-]+\=[a-z-A-Z0-9_\-\%\~\+]+)?)*)?";
////		Regex urlTest = new Regex(URL_REGEX, RegexOptions.IgnoreCase | RegexOptions.Compiled);
////		return urlTest.IsMatch(url);
////	}
//	public static boolean isPartOfDCMI(String strValue) {
//		//AMG - Check if it is a url
//		String key = "";
//		if (strValue.startsWith("http")) {
//			int index = strValue.lastIndexOf("/");
//			if (index == -1) {
//				//AMG - Bad URL
//				return false;
//			}
//			key = strValue.substring(index + 1, strValue.length());
//		} else key = strValue;
//
//		return MetadataUtilities.DCMI_ELEMENTS.containsKey(key);
//	}
}
